package com.bw.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.resp.ResponseResult;
import com.bw.entity.TbUser;
import com.bw.service.ITbUserService;
import com.bw.utils.auth.JwtUtils;
import com.bw.utils.auth.RsaUtils;
import com.bw.utils.auth.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ghq
 * @since 2020-05-31
 */
@RestController
@RequestMapping("/user")
public class TbUserController {
    @Autowired
    private ITbUserService tbUserService;

    @PostMapping("/login")
    public ResponseResult login(@RequestBody TbUser tbUser){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("username",tbUser.getUsername());
            queryWrapper.eq("pwd",tbUser.getPwd());
            TbUser tb = tbUserService.getOne(queryWrapper);
            if(tb!=null){
                result.setResult(tb);
                PrivateKey privateKey = RsaUtils.getPrivateKey("D:\\1711A\\keys\\rsa.pri");
                UserInfo userInfo = new UserInfo();
                userInfo.setId(tb.getId());
                userInfo.setUsername(tb.getUsername());
                String token = JwtUtils.generateToken(userInfo, privateKey, 30);
                Map mapinfo=new HashMap();
                mapinfo.put("user",tb);
                mapinfo.put("token",token);
                result.setResult(mapinfo);
                result.setMessage("登录成功");
            }else{
                result.setSuccess(false);
                result.setMessage("用户名或密码错误");
            }
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("登录失败");
        }
        return result;
    }
}
